//
//  CompleteView.m
//  OperationPro
//
//  Created by yaxue wang on 16/10/8.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "CompleteView.h"
#import "BankView.h"
#define _UIKeyboardFrameEndUserInfoKey (&UIKeyboardFrameEndUserInfoKey != NULL ? UIKeyboardFrameEndUserInfoKey : @"UIKeyboardBoundsUserInfoKey")
@implementation CompleteBtn

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUserInteractionEnabled:YES];
        [self setTextAlignment:NSTextAlignmentCenter];
        [self setFont:[UIFont systemFontOfSize:13]];
        [self.layer setBorderWidth:1];
        [self.layer setCornerRadius:5];
    }
    return self;
}

@end

@interface spaceLab : UITextView

@end

@implementation spaceLab

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[self nextResponder] touchesBegan:touches withEvent:event];
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
    return false;
}

@end

@interface CompleteView()<UIPickerViewDelegate,UIPickerViewDataSource,UITextViewDelegate>
{
    BankView *_bgView;
    
}
@property (nonatomic, strong)NSMutableArray *typeAr;
@property (nonatomic, strong) UIPickerView*pickerView;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) spaceLab *lblSpace;
@property (nonatomic, strong) UIView *boxView;
@property (nonatomic, strong) NSArray *btns;
@property (nonatomic, strong) NSString *place;
@property (nonatomic, strong) NSString *alertTitle;
@property (nonatomic, strong) NSString *alertType;
@property (nonatomic, strong) UILabel *typeLab;
@property (nonatomic, strong) NSString *type;
@property (nonatomic, strong) NSString *typeStr;
@property (nonatomic, strong) void(^action)(CompleteView *, NSInteger);
@end

@implementation CompleteView

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

- (instancetype)init{
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
        
    }
    return self;
}

+(CompleteView *) showInputBox:(NSString *)type place:(NSString *)place show:(NSString*)alertTitle showType:(NSString*)alertType btns:(NSArray *)btns action:(void(^)(CompleteView *boxView, NSInteger index))action{
    CompleteView *boxView = [[CompleteView alloc] init];
    boxView.action = action;
    boxView.btns = btns;
    boxView.place = place;
    boxView.type=type;
    boxView.alertTitle=alertTitle;
    boxView.alertType=alertType;
    [boxView showBox];
    return boxView;
}

- (void) initView{

    [CClass HttpRequestTask:YES withUrl:@"select_showFaultTypeSelect" withData:nil notifyError:YES onSuccess:^(BaseModel *model) {
        _typeAr=(NSMutableArray*)model.B_data;
        [_pickerView reloadAllComponents];
    } onError:^(BaseModel *model) {
        
    }];
    [self setBackgroundColor:[UIColor clearColor]];
    UIView *bgView = [[UIView alloc] initWithFrame:self.bounds];
    [self addSubview:bgView];
    [bgView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:.6]];
    
    float width = self.frame.size.width * 2 / 3;
    float height = 180;
    _boxView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
    [_boxView setBackgroundColor:[UIColor whiteColor]];
    [self addSubview:_boxView];
    [_boxView setCenter:self.center];
    
    [_boxView.layer setCornerRadius:5];
    
    float y = 0;

    _typeLab=[[UILabel alloc]initWithFrame:CGRectMake(15, y + 10, width - 30, 30)];
    _typeLab.text=@"选择故障类型";
    _typeLab.textColor=[UIColor blackColor];
    _typeLab.font= F(16);
    _typeLab.userInteractionEnabled=YES;
    [_boxView addSubview:_typeLab];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(typeAction:)];
    [_typeLab addGestureRecognizer:tap];

    UIImage *imgGO = [UIImage imageNamed:@"Ico_discuss_next"];
    UIImageView *goView = [[UIImageView alloc] initWithImage:imgGO];
    [_boxView addSubview:goView];
    [goView setCenter:CGPointMake(_boxView.frame.size.width - 15 - imgGO.size.width / 2, _typeLab.center.y)];
    [goView setUserInteractionEnabled:NO];
    y=40;
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(_typeLab.frame) + 10, width - 30, 90)];
    [_boxView addSubview:_textView];
    _textView.delegate=self;
    _textView.font=F(12);
    [_textView setBackgroundColor:C(@"eaeaea")];
    
    if (self.place) {
        _lblSpace = [[spaceLab alloc] initWithFrame:_textView.frame];
        [_boxView addSubview:_lblSpace];
        [_lblSpace setEditable:NO];
        [_lblSpace setText:self.place];
        [_lblSpace setTextColor:C(@"b9b7b7")];
        [_lblSpace setBackgroundColor:[UIColor clearColor]];
    }
    
    
    y +=  _textView.frame.size.height + 10;
    
    UIView *btnView = [[UIView alloc] initWithFrame:CGRectMake(15, y + 10, width - 30, 28)];
    [_boxView addSubview:btnView];
    if (self.btns == nil || self.btns.count == 0) {
        self.btns = @[@"确定"];
    }
    
    int i = 0;
    float btnspace = 10;
    float btnwidth = (width - 30 - btnspace * (self.btns.count - 1)) / self.btns.count;
    for (id btn in self.btns) {
        if ([btn isKindOfClass:[NSString class]]) {
            CompleteBtn *btnInput = [[CompleteBtn alloc] initWithFrame:CGRectMake(i * (btnwidth + btnspace) , 0, btnwidth, btnView.frame.size.height)];
            [btnView addSubview:btnInput];
            btnInput.tag = i;
            [btnInput setText:btn];
            btnInput.layer.borderWidth =0.5;
            if (i == 0) {
                [btnInput setTextColor:[UIColor whiteColor]];
                [btnInput setBackgroundColor:MainColor];
                btnInput.layer.masksToBounds=YES;
                btnInput.layer.cornerRadius=4;
                [[btnInput layer] setBorderColor:MainColor.CGColor];
            }else{
                [btnInput setTextColor:MainColor];
                [[btnInput layer] setBorderColor:MainColor.CGColor];
            }
            [btnInput setUserInteractionEnabled:YES];
            __block int weaki = i;
            [btnInput bk_whenTapped:^{
                if (self.action) {
                    if(weaki ==0)
                    {
                        if(_type==nil)
                        {
                            [CClass showMessage:self.alertType];
                            return;
                            
                        }
                        if ([_textView.text isEqualToString:@""]) {
                            [CClass showMessage:self.alertTitle];
                            return;
                        }else
                        {
                            [self hideBox];
                            
                        }
                        
                    }else
                    {
                        [self hideBox];
                        
                    }
                    self.action(self, weaki);
                }
            }];
        }else if([btn isKindOfClass:[CompleteBtn class]]){
            [btnView addSubview:btn];
            [btn setFrame:CGRectMake(i * (btnwidth + btnspace) , 0, btnwidth, btnView.frame.size.height)];
            [btn setUserInteractionEnabled:YES];
            __block int weaki = i;
            [btn bk_whenTapped:^{
                if (self.action) {
                    if(weaki ==0)
                    {
                        if(_type==nil)
                        {
                            [CClass showMessage:self.alertType];
                            return;
                            
                        }
                        if ([_textView.text isEqualToString:@""]) {
                            [CClass showMessage:self.alertTitle];
                            return;
                        }else
                        {
                            [self hideBox];
                            
                        }
                        
                    }else
                    {
                        [self hideBox];
                        
                    }
                    self.action(self, weaki);
                    
                }
            }];

        }
        i ++;
    }
    y += 10 + 28 + 10;
    
    CGRect boxFrame = _boxView.frame;
    boxFrame.size.height = y;
    [_boxView setFrame:boxFrame];
    
    _bgView =[[BankView alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, WindowHeight)witnOriginY:WindowHeight/3 withTitle:@"故障类型"];
    _bgView.backgroundColor=[UIColor clearColor];
    [self bringSubviewToFront:_bgView];
    [self addSubview:_bgView];
    _bgView.hidden=YES;
    _pickerView=[[UIPickerView alloc]initWithFrame:CGRectMake(0, 40, WindowWidth, WindowHeight/3-40)];
    _pickerView.delegate=self;
    _pickerView.dataSource=self;
    _pickerView.backgroundColor =[UIColor whiteColor];
    _pickerView.showsSelectionIndicator=YES;
    [_bgView.whiteView addSubview:_pickerView];
    __block typeof(self) blockself = self;

    [_bgView setSubmitBtnPress:^{
   
        
        int component0= [blockself.pickerView selectedRowInComponent:0];
        NSDictionary *dic =[blockself.typeAr objectAtIndex:component0];
        _typeStr=[dic objectForKey:@"type_name"];
        _type=[dic objectForKey:@"uuid"];
        blockself.typeLab.text=blockself.typeStr;
        blockself.typeLab.textColor=[UIColor blackColor];


    }];
}

- (id)inputData{
    return _textView.text;
}
- (id)typeData
{
    return _type;
}
- (void)typeAction:(UITapGestureRecognizer*)gesture
{
        _bgView.hidden=NO;
        [self endEditing:YES];
    int i = 0;
    for (NSDictionary *province in _typeAr) {
        if ([province[@"type_name"] isEqualToString:_typeLab.text]) {
            [_pickerView selectRow:i inComponent:0 animated:YES];
            break;
        }
        i ++;
    }
    if (i == _typeAr.count) {
        NSDictionary *dic =[_typeAr objectAtIndex:0];
        _typeStr=[dic objectForKey:@"type_name"];
        _type=[dic objectForKey:@"uuid"];
    }
    
    [UIView animateWithDuration:0.5 animations:^{
            _bgView.whiteView.frame=CGRectMake(0,WindowHeight/3*2 , WindowWidth, WindowHeight/3);
        } completion:nil];

}
- (void) btnAction:(UIGestureRecognizer *) button{
    NSInteger tag = button.view.tag;
    if (self.action) {
        if(tag ==0){
        if(_type==nil)
        {
            [CClass showMessage:self.alertType];
            return;
            
        }else if ([_textView.text isEqualToString:@""]) {
                [CClass showMessage:self.alertTitle];
                return;
            }else
            {
                [self hideBox];
                
            }
            
        }else
        {
            [self hideBox];
            
        }
        self.action(self, tag);
    }
}

- (void) showBox{
    [self initView];
    
    [[[UIApplication sharedApplication] keyWindow] addSubview:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ShowKeyboard:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(HideKeyboard:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TextChange:) name:UITextViewTextDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TextEndEdit:) name:UITextViewTextDidEndEditingNotification object:nil];
    
}

- (void) hideBox{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self removeFromSuperview];
}

- (void) ShowKeyboard:(NSNotification*)notification{
    CGRect keyboardRect = [self convertRect:[[[notification userInfo] objectForKey:_UIKeyboardFrameEndUserInfoKey] CGRectValue] fromView:nil];
    if (CGRectIsEmpty(keyboardRect)) {
        return;
    }
    if (keyboardRect.origin.y < CGRectGetMaxY(_boxView.frame)) {
        [UIView animateWithDuration:[[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
            CGRect frame = _boxView.frame;
            frame.origin.y = keyboardRect.origin.y - CGRectGetHeight(frame);
            _boxView.frame = frame;
        } completion:^(BOOL finished) {
            
        }];
    }
}

- (void) HideKeyboard:(NSNotification*)notification{
    CGRect keyboardRect = [self convertRect:[[[notification userInfo] objectForKey:_UIKeyboardFrameEndUserInfoKey] CGRectValue] fromView:nil];
    if (CGRectIsEmpty(keyboardRect)) {
        return;
    }
    
    [UIView animateWithDuration:[[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        [_boxView setCenter:self.center];
    } completion:^(BOOL finished) {
        
    }];
}

- (void) TextChange:(NSNotification *) notification{
    if (self.place && self.textView.text.length > 0) {
        [_lblSpace setHidden:YES];
    }else if(self.place && self.textView.text.length == 0){
        [_lblSpace setHidden:NO];
    }
}

- (void) TextEndEdit:(NSNotification *) notification{
    if ([self.textView.text isEqualToString:self.place] || [self.textView.text isEqualToString:@""]) {
        self.textView.text = @"";
        [_lblSpace setHidden:NO];
    }
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
    
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 35;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    return _typeAr.count;
    
}
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    
    NSDictionary *dic =[_typeAr objectAtIndex:row];
    return [dic objectForKey:@"type_name"];
    
    
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
   
    
    
}
- (void)textViewDidChange:(UITextView *)textView{
    if ([CClass stringContainsEmoji:textView.text]) {
        textView.text=[textView.text substringToIndex:textView.text.length-2];
        return;
    }
    if (textView.markedTextRange == nil && textView.text.length > 20)  //加上 textView.markedTextRange == nil判断，当此属性为nil时，代表不在这种联想输入等待确定状态。
        
    {
        
        textView.text = [textView.text substringToIndex:20];
        
    }
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
        if ([[[UITextInputMode currentInputMode]primaryLanguage] isEqualToString:@"emoji"]) {
            return NO;
        }


    return YES;
    
}


@end

